package com.gonsin.gview.general.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class CmdUtils {

    /**
     * 读取命令行
     * @return
     */
    public static String readCmd(String message, boolean nullable){
        String out = null;
        do {
            System.out.println(message);
            StringBuffer sb = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            char c = 0;
            do {
                try {
                    c = (char) br.read();
                    if(c != '\n'){
                        sb.append(c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } while (c != '\n');
            out = sb.toString();
        } while ("".equals(out) && !nullable);
        return out;
    }


    /**
     * 读取成true/false
     * @param message
     * @param nullable
     * @return
     */
    public static boolean readBoolean(String message, boolean defaultValue){
        String out = null;
        do {
            System.out.println(message);
            StringBuffer sb = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            char c = 0;
            do {
                try {
                    c = (char) br.read();
                    if(c != '\n'){
                        sb.append(c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } while (c != '\n');
            out = sb.toString();
            if(!Arrays.asList("Y", "y", "N", "n", "").contains(out)){
                System.out.println("无效输入，必须是 \"Y\", \"y\", \"N\", \"n\", \"\" 其中之一");
            } else {
                break;
            }
        } while (true);

        if(StringUtils.isEmpty(out)){
            return defaultValue;
        }

        out = out.equalsIgnoreCase("y") ? "true" : "false";

        return BooleanUtils.toBoolean(out);
    }


}
